<template>
  <el-form
    ref="registryForm"
    class="registry"
    :model="registryForm"
    :rules="registryRules"
  >
    <el-form-item prop="nickname">
      <el-input
        placeholder="取个名字吧"
        v-model.trim="registryForm.nickname"
      ></el-input>
    </el-form-item>
    <el-form-item prop="phone">
      <el-row>
        <el-col :span="7">
          <el-select v-model="countrycode">
            <el-option-group
              v-for="group in countrycodes"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.countryList"
                :key="item.code"
                :value="item.code"
              >
                <span style="float: left">{{ item.zh }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.code
                }}</span>
              </el-option>
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="16" :offset="1">
          <el-input
            placeholder="网易云音乐手机号"
            @input="checkPhone"
            v-model.trim="registryForm.phone"
          ></el-input>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        :type="toggleType"
        placeholder="填写密码"
        v-model.trim="registryForm.password"
      >
        <template slot="append">
          <div @click.stop="toggleInputType" class="icon-wrap">
            <i class="iconfont icon-eye"></i>
          </div>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="captcha">
      <el-row>
        <el-col :span="14">
          <el-input
            placeholder="验证码"
            v-model="registryForm.captcha"
          ></el-input>
        </el-col>
        <el-col :span="9" :offset="1">
          <el-button
            class="get-captcha"
            :class="{ normal: !isDisable }"
            :disabled="isDisable"
            @click.stop="getCaptcha"
          >
            <span v-show="isDisable === false">发送验证码</span>
            <span v-show="isDisable === true">{{ timeOut }}s 秒后重发</span>
          </el-button>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item prop="isRead">
      <el-checkbox v-model="registryForm.isRead"></el-checkbox>
      <span class="protocol">已阅读并同意《神马音乐 食用说明》</span>
    </el-form-item>
    <el-form-item>
      <el-button class="registry-btn" @click="registryBtn">快速注册</el-button>
    </el-form-item>
    <el-form-item style="text-align:center">
      已有账号,
      <span class="return-login" @click.stop="returnLogin">返回登录</span>
    </el-form-item>
  </el-form>
</template>
<script>
import countrycodes from '@/utlis/countrycodes'
import { getCaptcha, verifyCode, registryID, check } from '@/api/registry_login'
const _PHONE = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
export default {
  name: 'registry',
  data () {
    return {
      // 手机号是否注册
      isExist: false,
      // 是否禁用按钮
      isDisable: false,
      // 倒计时
      timeOut: 61,
      // 国家码
      countrycodes,
      // 是否显示密码
      toggleType: 'password',
      // 用户是否阅读协议
      // 摆设国家码
      countrycode: '86',
      // 表单属性
      registryForm: {
        nickname: null, // 昵称
        phone: null, // 手机号码
        password: null, // 密码
        captcha: null, // 验证码
        isRead: null
      },
      registryRules: {
        nickname: [
          { required: true, message: '给自己取个名', trigger: 'blur' },
          { min: 1, max: 11, message: '用户名请设置 1 ~ 11 位' }
        ],
        phone: [
          { required: true, message: '手机号要输入啊!', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const PHONE_RULE = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (PHONE_RULE.test(value)) {
                callback()
              } else {
                callback(new Error('手机号码格式不正确'))
              }
            },
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (!this.isExist) {
                callback()
              } else {
                callback(new Error('该手机号已被注册'))
              }
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码呢!', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '请输入 6 ~ 20 位密码',
            trigger: 'blur'
          }
        ],
        captcha: [
          { required: true, message: '验证码填一下啦', trigger: 'blur' }
        ],
        isRead: [
          {
            validator: (ruel, value, callback) => {
              if (value) {
                callback()
              } else {
                callback(new Error('请阅读协议并勾选'))
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  methods: {
    // 验证手机号是否注册
    async checkPhone () {
      if (_PHONE.test(this.registryForm.phone)) {
        const data = await check({
          phone: this.registryForm.phone
        })
        if (data.exist === 1) {
          this.isExist = true
        } else {
          this.isExist = false
        }
      }
    },
    // 注册、
    registryBtn () {
      this.$refs.registryForm.validate(async result => {
        if (result) {
          // 验证通过 发送请求
          try {
            // 验证验证码是否正确
            const data = await verifyCode({
              phone: this.registryForm.phone,
              captcha: this.registryForm.captcha
            })
            if (data.code === 200) {
              registryID({
                captcha: this.registryForm.captcha,
                phone: this.registryForm.phone,
                password: this.registryForm.password,
                nickname: this.registryForm.nickname
              })
                .then(res => {
                  this.$message.success('注册成功,赶紧登录吧!')
                  setTimeout(() => {
                    this.returnLogin()
                  }, 1500)
                })
                .catch(err => {
                  window.console.log(err)
                })
            } else {
              console.log('注册出错了')
            }
          } catch (err) {
            window.console.log(err)
          }
        }
      })
    },
    // 获取验证码
    async getCaptcha () {
      window.console.log('验证码')
      let hasPhone = false
      this.$refs.registryForm.validateField(['phone'], err => {
        if (err === '') {
          hasPhone = true
        }
      })
      if (hasPhone) {
        this.timeOut--
        if (this.timeOut !== 61) {
          this.isDisable = true
        }
        const timeId = setInterval(() => {
          this.timeOut--
          if (this.timeOut <= 0) {
            clearInterval(timeId)
            this.isDisable = false
            this.timeOut = 61
          }
        }, 1000)
        await getCaptcha({
          phone: this.registryForm.phone
        })
      }
    },
    // 返回登录框
    returnLogin () {
      this.$emit('setMode', 'login')
    },
    toggleInputType () {
      if (this.toggleType === 'password') {
        this.toggleType = 'text'
      } else {
        this.toggleType = 'password'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-select-group .el-select-dropdown__item {
  padding: 0 20px;
}
.registry {
  width: 330px;
  margin: 0 auto;

  .get-captcha {
    width: 100%;
    &.normal {
      background-color: @btn-bg-color;
      color: #63dbc1;
      &:hover {
        background-color: @btn-hover;
      }
    }
  }
  .protocol {
    margin-left: 10px;
    margin-top: 2px;
  }
  .registry-btn {
    width: 100%;
    background-color: @btn-bg-color;
    color: #63dbc1;
    &:hover {
      background-color: @btn-hover;
    }
  }
  .return-login {
    cursor: pointer;
    color: @main-font-color;
    &:hover {
      color: black;
    }
  }
  /deep/ .el-input-group__append {
    position: relative;
    width: 50px;
    padding: 0;
    .icon-wrap {
      cursor: pointer;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      &:hover {
        background-color: #eeeeee;
      }
    }
  }
}
</style>
